package com.project.controller.web;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.project.common.utils.Constants;
import com.project.common.utils.MyPageHelper;
import com.project.common.utils.PublicUtils;
import com.project.common.validator.ValidatorUtils;
import com.project.common.validator.group.AddGroup;
import com.project.entity.Resource;
import com.project.entity.User;
import com.project.entity.UserRole;
import com.project.myBeans.R;
import com.project.myBeans.ResponseBean;
import com.project.service.UserRoleService;
import com.project.service.UserService;
import com.project.service.base.BaseService;
import com.project.service.base.Captcha.CaptchaService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.http.HttpStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@EnableAutoConfiguration //自动载入应用程序所需的所有Bean
@RestController //@Controller与@ResponseBody的合并
@RequestMapping(value = "/user")
@Api(description = "用户管理接口",value = "user")
public class UserController extends BaseService {

    @Autowired
    UserService userService;

    @Autowired
    private UserRoleService userRoleService;

    @Autowired
    CaptchaService captchaService;

    /**
     * TateBrown 2018年5月25日
     *
     * @param user
     * @return
     */
    @ApiOperation("修改用户密码")
    @PostMapping("/modifyPwd")
    public R modifyPwd(@RequestBody User user){
        try{
           User oldUser =userService.findOneAllByUserID(user.getId());
            if(!userService.validatePassword(oldUser,user.getPassword())){
                return R.error(HttpStatus.SC_METHOD_FAILURE,"原密码不正确");
            }else{
                if(!user.getNewPassword().equals(user.getCheckNewPassword())){
                    return R.error(HttpStatus.SC_CONFLICT,"新密码与确认密码不同");
                }else{
                    user.setPassword(user.getNewPassword());
                    userService.updateUser(user);
                    return R.ok("密码修改成功");
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            return R.error("失败");
        }
    }

    /**
     * TateBrown 2018年5月25日
     *
     * @param user
     * @return
     */
    @ApiOperation("重置密码")
    @PostMapping("/resetPassword")
    public R resetPassword(@RequestBody User user){
        try{
            user.setPassword(user.getPassword());
            userService.updateUser(user);
            return R.ok("重置成功");
        }catch(Exception e){
            e.printStackTrace();
            return R.error("程序异常");
        }
    }

    /**
     * TateBrown 2018年5月25日
     *
     * @param user
     * @return
     */
    @ApiOperation("注册用户")
    @PostMapping("/registerUser")
    public R registerUser(@RequestBody User user) throws  Exception{
        try{
            if (!userService.checkUsernameAndUniversityIdIsExist(user.getUsername(), user.getUniversityid())){
                userService.createUser(user);

                //企业注册
                if (user.getUsertype() == Constants.USERTYPE.ORG.value()){
                    //用户权限表插入
                    UserRole userRole = new UserRole();
                    userRole.setUserid(user.getId());
                    userRole.setRoleid(Constants.USERTYPE.ORG.value());
                    userRoleService.add(userRole);
                }
                return R.ok("注册成功");
            }
            else{
                return R.error("账户已存在");
            }
        }catch (Exception e){
            e.printStackTrace();
            return R.error("程序异常");
        }
    }

    /**
     * TateBrown 2018年5月25日
     *
     * @param username
     * @return true-存在,false-不存在
     */
    @ApiOperation("检查用户名是否存在")
    @PostMapping("/checkUsername")
    public R checkUsername(@PathVariable("username") String username){
        try{
            System.out.println("user name==="+username);

            if(userService.checkUsernameIsExist(username)){
                return R.ok("存在");
            }else{
                return R.error("不存在");
            }

        }catch(Exception e){
            e.printStackTrace();
            return R.error("程序异常");
        }
    }

    /**
     * TateBrown 2018年5月25日
     *
     * @param id
     * @return
     */
    @ApiOperation("根据id查找用户详细信息")
    @PostMapping("/findOneById/{id}")
    public R findOneById(@PathVariable("id") Integer id){
        try{
            return R.ok("获取成功").put("data",userService.findOneByUserID(id));
        }catch(Exception e){
            e.printStackTrace();
            return R.error("程序异常");
        }
    }

    /**
     * TateBrown 2018年5月25日
     *
     * @param user
     * @return
     */
    @ApiOperation("修改用户表信息")
    @PostMapping("/modifyOne")
    public R modifyOne(@RequestBody User user){
        try{
            if(checkDeleteUpdateIsSuccess(userService.updateUser(user))){
                return R.ok("修改成功");
            }
            else{
                return R.error("修改失败");
            }
        }catch (Exception e){
            e.printStackTrace();
            return R.error("程序异常");
        }
    }
    /**
     * TateBrown 2018年5月25日
     *
     * @param user
     * @return
     */
    @ApiOperation("根据条件查找用户")
    @PostMapping("/findBatchByCondition")
    public R findBatchByCondition(@RequestBody User user){
        try{
            MyPageHelper.setPageParam(user);
            List<User> list=userService.findBatchByCondition(user);
            return R.ok("查找成功").put("data",list).put("total",MyPageHelper.getTotal(list));
        }catch (Exception e){
            e.printStackTrace();
            return R.error("程序异常");
        }
    }
    /**
     * TateBrown 2018年5月25日
     *
     * @param userid
     * @return
     */
    @ApiOperation("获取菜单")
    @PostMapping("/getMenus/{userid}")
    public Object getMenus(@PathVariable("userid") Integer userid){
        try{
            List<Resource> resourceList=userService.getMenu(userid);
            List<Resource> resourceList2=createTree(resourceList);
            return R.ok("生成成功").put("data",resourceList2);
        }catch(Exception e){
            e.printStackTrace();
            return R.error("程序异常").put("data",null);
        }
    }
    //构建菜单树函数
    public List<Resource> createTree(List<Resource> resourceList) {
        List<Resource> nodeList = new ArrayList<Resource>();
        for (Resource resource1 : resourceList) {
            boolean mark = false;
            for (Resource resource2 : resourceList) {
                if (resource1.getPid().equals(resource2.getId())) {
                    mark = true;
                    if (resource2.getChildren() == null) {
                        resource2.setChildren(new ArrayList<Resource>());
                    }
                    resource2.getChildren().add(resource1);
                    break;
                }
            }
            if (!mark) {
                nodeList.add(resource1);
            }

        }
        return nodeList;
    }
    /**
     * TateBrown 2018年5月25日
     *
     * @param user
     * @return
     */
    @ApiOperation("忘记密码修改密码")
    @PostMapping("/updateForPWD")
    public R updateForPWD(@RequestBody User user){
        try{
            System.out.println("user==="+JSON.toJSONString(user));

            if(StringUtils.isEmpty(user.getUsername())||StringUtils.isEmpty(user.getUniversityid().toString())){
                return R.error("用户名或大学不能为空！");
            }
            User user1=userService.findOneByUserNameAndUniversityId(user.getUsername(),user.getUniversityid());
            if(user1==null){
                return R.error("用户不存在");
            } else{
              String code=captchaService.getCaptchaValueByUserid(user1.getId());
              if(!code.equals(user.getCaptchaCode())){
                  return R.error("验证码无效");
              }else{
                  user.setPassword(user.getNewPassword());
                  user.setId(user1.getId());
                  userService.updateUser(user);
                  return R.ok("找回密码成功！");
              }
            }

        }catch (Exception e){
            e.printStackTrace();
            return  R.error("找回失败请重试");
        }
    }
}
